<?php

namespace App\Jobs;

use App\Models\User\WxUser;
use App\Models\User\WxUserFollow;
use App\Wen\Utils\GatewayUtils;
use App\Wen\Utils\UserUtils;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class UserOnlineBroadcastJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $tries = 1;
    protected $online_user_id = 0;
    protected $online_client_id = 0;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($user_id, $client_id)
    {
        //
        $this->online_user_id = $user_id;
        $this->online_client_id = $client_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
        if(_empty_($this->online_user_id) && _empty_($this->online_client_id)){
            return;
        }

        if(_empty_($this->online_user_id)){
            $this->online_user_id = GatewayUtils::client_id2uid($this->online_client_id);
        }else if(_empty_($this->online_client_id)){
            $this->online_client_id = GatewayUtils::uid2client_id($this->online_user_id);
        }

        if($this->online_user_id){
            $onlines = UserUtils::user_onlines(1);
            if($onlines){
                $user_ids = WxUserFollow::whereIn('id', $onlines)->where([
                    ['user_follow_id', '=', $this->online_user_id],
                    ['user_follow_state', '=', 0]
                ])->pluck('user_id')->toArray();
                if($user_ids){
                    $user_name = WxUser::where('id', $this->online_user_id)->value('user_name');
                    foreach ($user_ids as $user_id){
                        if($this->online_user_id != $user_id){
                            GatewayUtils::info_message(GatewayUtils::uid2client_id($user_id), '您关注的「'.$user_name.'」已上线');
                        }
                    }
                }
            }
        }

    }
}
